package com.apes.framework.plugin.form.parser.matcher;

import com.apes.framework.util.Operation;
import com.apes.framework.util.Tools;

/**
 * 功能：真假值表达式模式匹配器
 *
 * @author xul
 * @create 2018-04-19 17:23
 */
public class ExpressionMatcher implements Matcher<String, String> {
    private static final String placeholder = "{~@#$%^&*}";  //变量占位符

    private Matcher parent;

    /**
     * 功能：获取识别模式
     */
    @Override
    public String getRegex() {
        return ",";
    }

    @Override
    public Matcher getParent() {
        return parent;
    }

    @Override
    public void setParent(Matcher parent) {
        this.parent = parent;
    }

    /**
     * 功能：模式配置
     *
     * @param content
     */
    @Override
//    @Timer("解析真假值表达式")
    public String parse(String content) {
        String[] values = content.split(getRegex());
        if (values.length < 3) throw new RuntimeException("表达式：" + content + "输入错误！");
        String left = placeholder + values[0].trim().replace("'", "");
        String operation = values[1].trim().replace("'", "");
        if (Tools.isNull(Operation.getTsType(operation))) throw new RuntimeException("表达式：" + content + "输入错误！");
        StringBuilder sb = new StringBuilder(); //.append("(")
        if (operation.equals("in") || operation.equals("not in")) {
            sb.append(operation.equals("in") ? "" : Operation.getTsType("!")).append("(");
            for (int i = 2; i < values.length; i++) {
                sb.append("(").append(left).append(Operation.getTsType("=")).append(values[i].trim()).append(")");
                if (i < values.length - 1) sb.append(" ").append(Operation.getTsType("|")).append(" ");
            }
            sb.append(")");
        } else {
            sb.append(left).append(" ").append(Operation.getTsType(operation)).append(" ").append(values[2].trim());
        }
        //sb.append(")");
        return sb.toString();
    }

    public static String getPlaceholder() {
        return placeholder;
    }
}
